<?php
require_once(SITE_ROOT . 'class/db/DB.class.php');
require_once(SITE_ROOT . 'class/bean/Country.class.php');

class DBHCountry {
	
	public function getCountries($date) {
		$db = new DB();
		$connection = $db->connect();
		$stmt =  $connection->stmt_init();
		
		if ($stmt->prepare('SELECT `country#`, `seasons`, `divisions`, `activeusers`, `waitingusers`, `date#` FROM `hcountry` WHERE `date#` = ? ORDER BY `activeusers`')) {
			$stmt->bind_param('s', $date);
			$stmt->execute();
			$stmt->bind_result($countryID, $seasons, $divisions, $activeusers, $waitingusers, $date);
			
			$countries = array();
			
			while ($stmt->fetch()) {
				$country = new Country();
				$country->setCountryID($countryID);
				$country->setSeasons($seasons);
				$country->setDivisions($divisions);
				$country->setActiveUsers($activeusers);
				$country->setWaitingUsers($waitingusers);
				$country->setDate(strtotime($date));
				$countries[$country->getCountryID()] = $country;
			}			
			$stmt->close();
			$db->disconnect();
			
			return $countries;
		}
	}
	
	public function saveCountries($countries) {
		$db = new DB;
		$connection = $db->connect();
		
		if ($stmt = $connection->prepare('INSERT INTO `hcountry` (`country#`, `seasons`, `divisions`, `activeusers`, `waitingusers`, `date#`) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE `seasons`=VALUES(`seasons`), `divisions`=VALUES(`divisions`), `activeusers`=VALUES(`activeusers`), `waitingusers`=VALUES(`waitingusers`)')) {
			$stmt->bind_param('iiiiis', $countryID, $seasons, $divisions, $activeusers, $waitingusers, $date);
			foreach ($countries as $country) {
				$countryID = $country->getCountryID();
				$seasons = $country->getSeasons();
				$divisions = $country->getDivisions();
				$activeusers = $country->getActiveUsers();
				$waitingusers = $country->getWaitingUsers();
				$date = date('Y-m-d', $country->getDate());
				
				$stmt->execute();
			}
			$stmt->close();
			$db->disconnect();
		}
	}
	

}

?>